package cn.max.web.listeners;

import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;

/**
 * Application Lifecycle Listener implementation class DBInitiator
 *
 */
public class DBInitiator implements ServletContextListener {
	
	private static SqlSessionFactory ssf;
	
    public void contextInitialized(ServletContextEvent arg0) {
		Configuration configuration;
		try {
			configuration = new XMLConfigBuilder(Resources.getResourceAsReader("dbconf.xml"), null, null).parse();
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			
			ssf = builder.build(configuration);
			
			System.out.println("DB INITED");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
    }
    
    public static void main(String[] args) {
		new DBInitiator().contextInitialized(null);
		
		SqlSession session = DBInitiator.getSqlSession();
		
//		ClientTokenMapper mapper = session.getMapper(ClientTokenMapper.class);
//		ClientToken ct = new ClientToken();
//		ct.setClientCode("admin");
//		ct.setToken("password");
//
//		System.out.println(mapper.insert(ct));
		
		session.commit();
		session.close();
		
		System.out.println("done.");
	}
    
    public static SqlSession getSqlSession() {
    	return ssf.openSession();
    }
    
    public static SqlSession getSqlSession(boolean autocommit) {
    	return ssf.openSession(autocommit);
    }

    public void contextDestroyed(ServletContextEvent arg0) {
    }
	
}
